package com.zhiyin.game.Service;

import com.zhiyin.game.bean.Cell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
public class GameService {

    private Logger logger = LoggerFactory.getLogger(GameService.class);

    @Autowired
    private MapService mapService;

    @Autowired
    private CellService cellService;

    @Autowired
    private BankService bankService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    private String field = "zhiyin:game:setting";


    /**
     * 初始化地图
     * @param width
     * @param height
     * @param bankSize
     * @return
     */
    public Map initData(int width, int height, int bankSize) {
        //初始化地图数据
        Cell[][] map = mapService.initMapData(width, height);
        //填充墙的数据
        Cell[][] cells = cellService.initCellData(width, height, map);
        //填充银行的数据
        cells = bankService.initBankData(bankSize, cells);

        //封装返回数据
        Map resultMap = new HashMap();
        resultMap.put("mapInfo", cells);
        //填充角色数据
        resultMap.putAll(roleService.initRoleData(cells));
        return resultMap;
    }

    /*
    * interval 间隔（s）
    * steps 步数
    * music 音乐1开启,0关闭
    * level 游戏等级 1低 2中 3高
    * */
    public void saveSetting(Map params){
        long time = 1800;
        Iterator mapKeys = params.keySet().iterator();
        while (mapKeys.hasNext()){
            String mapKey = mapKeys.next().toString();
            int value = Integer.parseInt(String.valueOf(params.get(mapKey)));
            logger.info("GameService:gameSetting     " + mapKey + ":" + params.get(mapKey));
            redisTemplate.opsForHash().put(field,mapKey,value);
        }
        if (params.size() > 0){
            redisTemplate.expire(field, time, TimeUnit.SECONDS);
        }
    }

    public Map getSetting(Map params){
        Map resultMap = new HashMap();
        List<Map> rows = new ArrayList();
        Map map = new HashMap();
        Set<Object> keys = redisTemplate.opsForHash().keys(field);
        Iterator iterator =  keys.iterator();
        while (iterator.hasNext()){
            String key = iterator.next().toString();
            map.put(key,redisTemplate.opsForHash().get(field,key));
        }
        rows.add(map);
        resultMap.put("rows",rows);
        return resultMap;
    }

}
